const PACKAGE_ID_JD = "com.jingdong.app.mall";
const ACTIVITY_ID = "com.jingdong.app.mall.WebActivity";

const WEEK_DAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// 任务关键字
const KEYWORD_MATCH = /.*可得(\d+-*\d*)金币$/;
const TIME_BROWES = 10000; // 浏览时间
const TIME_WAIT = 1000; // 界面切换等待的时间
const TIME_OUT = 30; // 超时时间

// 任务类型
const TASK_TYPE = {
  ToShare: 1, // 邀请好友助力
  Browse: 2, // 浏览
  BrowseForWhile: 3, // 浏览一段时间
  BrowseProducts: 4, // 浏览几个商品
  ReturnTwoTimes: 5, // 需要2次返回才能退出的界面
  AddMarketCar: 6, // 添加购物车
  SeeShop: 7, // 逛店铺
  JoinMember: 8, // 加入会员
  ClockIn: 9, // 打卡
  OrganizeTeam: 10, // 去组队
  GoHome: 11, // 去首页
  Shopping: 12, // 下单
  PlayGame: 13, // 玩游戏
  GotoMiniProgram: 14, // 去小程序
  JumpApp: 15 // 跳转其他App
};

let timerThread;  // 计时器线程
let timeout = 0;  // 计数

main();

function main() {

  // 检查无障碍权限
  auto.waitFor();

  console.log("本地时间: " + getCurrentDate() + " " + getCurrentTime());
  console.log("开始京东任务");

  stayTimer();

  while (true) {
    checkTimeout();
    viewTask();
  }
}

function openJingdong() {
  if (currentPackage() == PACKAGE_ID_JD) {
    console.log("已经在" + app.getAppName(PACKAGE_ID_JD) + "里");
    return;
  }
  app.launchPackage(PACKAGE_ID_JD);
  console.log("正在启动" + app.getAppName(PACKAGE_ID_JD) + "...");
  sleep(5000);
}

function shutdownJingdong() {
  app.openAppSetting(PACKAGE_ID_JD);
  text("京东").waitFor();
  const closeButton = textContains("强行停止").findOne();
  if (closeButton.enabled()) {
    closeButton.click();
    const confirmButton = textContains("确定").findOne();
    confirmButton.click();
    console.log("京东已被关闭");
    home();
  } else {
    console.log("京东未能被正常关闭或不在后台运行");
    home();
  }
  sleep(TIME_WAIT);
}

function openWebActivity() {
  console.log("正在打开活动界面...");
  click(1380, 2260);
  sleep(10000);
  console.log("正在打开任务列表...");
  click(1250, 2450);
  sleep(1000);
}

function stayTimer() {
  timerThread = threads.start(function () {
    setInterval(function () { timeout++; }, 1000);
  });
  sleep(TIME_WAIT);
}

function checkTimeout() {
  if (timeout > TIME_OUT) {
    timerThread.interrupt();
    log("停留某个页面超过30s, 退出脚本");

    exit();
  }
}

function viewTask() {
  if (textMatches(KEYWORD_MATCH).exists()) {
    sleep(TIME_WAIT);
    let widgets = textMatches(KEYWORD_MATCH).find();
    for (let index = 0; index < widgets.length; index++) {
      let widget = widgets[index];
      let widgetParent = widget.parent();
      let progress = widgetParent.child(1).text();
      let describe = widgetParent.child(2).text();
      let num = parseInt(progress.match(/\d+(?=\/)/g));
      let total = parseInt(progress.match(/\d+(?=\))/g));
      //log(progress + " " + describe);

      if (num < total) {
        let taskType = checkTaskType(progress, describe);

        // 忽略一些任务
        if (taskType == TASK_TYPE.GoHome || taskType == TASK_TYPE.ToShare || taskType == TASK_TYPE.Shopping || taskType == TASK_TYPE.JumpApp) {
          continue;
        }

        let buttonWidget = widgetParent.child(3);
        //click(buttonWidget.bounds().centerX(), buttonWidget.bounds().centerY());
        if (buttonWidget.click()) {
          timeout = 0; // 点击任务 重置计时
          log("正在进行任务:" + progress.match(/.*(?=\()/) + " " + (num + 1) + "/" + total + " " + describe);
          sleep(TIME_WAIT + 3000);

          if (taskType == TASK_TYPE.Browse) {
            returnNow();
          } else if (taskType == TASK_TYPE.BrowseForWhile || taskType == TASK_TYPE.PlayGame) {
            returnLater();
          } else if (taskType == TASK_TYPE.BrowseProducts) {
            browseProducts(4);
          } else if (taskType == TASK_TYPE.ReturnTwoTimes) {
            returnTwoTimes();
          } else if (taskType == TASK_TYPE.GotoMiniProgram) {
            returnTwoTimes();
          } else if (taskType == TASK_TYPE.AddMarketCar) {
            addMarketCar(4);
          } else if (taskType == TASK_TYPE.SeeShop) {
            seeShop(3);
          } else if (taskType == TASK_TYPE.ClockIn || taskType == TASK_TYPE.OrganizeTeam) {
            onlyClick();
          } else if (taskType == TASK_TYPE.JoinMember) {
            joinMember();
          } else {
            returnNow();
          }
        }
      }
      sleep(TIME_WAIT);
    }
  }
}

function checkTaskType(progress, describe) {
  let taskType = TASK_TYPE.Browse;
  if (/^(浏览).*\d+s/.test(describe)) {
    taskType = TASK_TYPE.BrowseForWhile;
  } else if (/浏览\d+个商品/.test(describe)) {
    taskType = TASK_TYPE.BrowseProducts;
  } else if (/浏览可得/.test(describe)) {
    if (/逛大牌店铺/.test(progress)) {
      taskType = TASK_TYPE.SeeShop;
    } else if (/去开通.*会员/.test(progress)) {
      taskType = TASK_TYPE.JoinMember;
    } else if (/去京东金榜/.test(progress)) {
      taskType = TASK_TYPE.BrowseForWhile;
    } else if (/去瓜分3亿红包/.test(progress)) {
      taskType = TASK_TYPE.ReturnTwoTimes;
    } else {
      taskType = TASK_TYPE.Browse;
    }
  } else if (/加购\d+个商品/.test(describe)) {
    taskType = TASK_TYPE.AddMarketCar;
  } else if (/每邀\d+个好友/.test(describe)) {
    taskType = TASK_TYPE.ToShare;
  } else if (/打卡/.test(describe)) {
    taskType = TASK_TYPE.ClockIn;
  } else if (/组队/.test(describe)) {
    taskType = TASK_TYPE.OrganizeTeam;
  } else if (/首页浮层/.test(describe)) {
    taskType = TASK_TYPE.GoHome;
  } else if (/下单/.test(describe)) {
    taskType = TASK_TYPE.Shopping;
  } else if (/玩.*游戏/.test(describe)) {
    taskType = TASK_TYPE.PlayGame;
  } else if (/小程序/.test(describe)) {
    taskType = TASK_TYPE.GotoMiniProgram;
  }
  return taskType;
}

function returnNow() {
  sleep(TIME_WAIT);
  back();
}

function returnTwoTimes() {
  sleep(TIME_BROWES);
  back();
  sleep(TIME_WAIT);
  back();
}

function returnThreeTimes() {
  sleep(TIME_BROWES);
  back();
  sleep(TIME_WAIT);
  back();
  sleep(TIME_WAIT);
  back();
}

function returnLater() {
  sleep(TIME_BROWES);
  back();
}

function onlyClick() {
  sleep(TIME_WAIT);
}

function browseProducts(count) {
  if (textContains('¥').exists()) {
    sleep(TIME_WAIT);
    let widgets = textContains('¥').find();
    for (let index = 0; index < widgets.length; index++) {
      if (index == count) {
        sleep(TIME_WAIT);
        back();
        break;
      }
      sleep(TIME_WAIT);
      let widget = widgets[index];
      let widgetParent = widget.parent().parent();
      let buttonWidget = widgetParent.child(4);
      if (buttonWidget.click()) {
        log("    浏览第" + (index + 1) + "个商品");
        sleep(TIME_WAIT + 1000);
        back();
      }
    }
  }
}

function addMarketCar(count) {
  if (textContains('¥').exists()) {
    sleep(TIME_WAIT);
    let widgets = textContains('¥').find();
    for (let index = 0; index < widgets.length; index++) {
      if (index == count) {
        sleep(TIME_WAIT);
        back();
        break;
      }
      sleep(TIME_WAIT);
      let widget = widgets[index];
      let widgetParent = widget.parent().parent();
      let buttonWidget = widgetParent.child(4);
      if (buttonWidget.click()) {
        log("    加购第" + (index + 1) + "个商品");
        sleep(TIME_WAIT + 1000);
        back();
      }
    }
  }
}

function seeShop(count) {
  if (textContains('自营').exists()) {
    sleep(TIME_WAIT);
    let widgets = textContains('自营').find();
    for (let index = 0; index < widgets.length; index++) {
      if (index == count) {
        sleep(TIME_WAIT);
        back();
        break;
      }
      sleep(TIME_WAIT);
      let widget = widgets[index];
      // let widgetParent = widget.parent();
      // let buttonWidget = widgetParent.child(4);
      let widgetParent = widget.parent().parent();
      let buttonWidget = widgetParent.child(2);
      if (buttonWidget.click()) {
        log("    逛第" + (index + 1) + "个店铺");
        sleep(TIME_WAIT + 1000);
        back();
      }
    }
  }
}

function joinMember() {
  if (textContains('确认授权并加入店铺会员').exists()) {
    sleep(TIME_WAIT);
    let buttonWidget = textContains('确认授权并加入店铺会员').findOne();
    if (!!buttonWidget) {
      let bounds = buttonWidget.parent().parent().child(5).bounds();
      click(bounds.centerX(), bounds.centerY());
    }
    sleep(TIME_WAIT);
    click(buttonWidget.bounds().centerX(), buttonWidget.bounds().centerY());

    sleep(TIME_WAIT);
    back();
  } else {
    sleep(TIME_WAIT);
    back();
  }
}

function dateDigitToString(num) {
  //return num < 10 ? '0' + num : num;
  return num.toString().padStart(2, '0');
}

function getCurrentTime() {
  const currentDate = new Date();
  const hours = dateDigitToString(currentDate.getHours());
  const minute = dateDigitToString(currentDate.getMinutes());
  const second = dateDigitToString(currentDate.getSeconds());
  const formattedTimeString = hours + ':' + minute + ':' + second;
  return formattedTimeString;
}

function getCurrentDate() {
  const currentDate = new Date();
  const year = dateDigitToString(currentDate.getFullYear());
  const month = dateDigitToString(currentDate.getMonth() + 1);
  const date = dateDigitToString(currentDate.getDate());
  const week = currentDate.getDay();
  const formattedDateString = year + '-' + month + '-' + date + '-' + WEEK_DAY[week];
  return formattedDateString;
}
